package org.tobuy.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.tobuy.dao.IScoreDAO;
import org.tobuy.vo.Item;
import org.tobuy.vo.Score;
import org.tobuy.vo.User;

public class ScoreDAOImpl implements IScoreDAO{
	
	private Connection conn = null;
	private PreparedStatement pstmt = null;
	ResultSet rs = null;
	public ScoreDAOImpl(Connection conn){
		this.conn = conn;
	}
	
	
	public boolean addScore(Score score) throws Exception {
		boolean flag = false;
		String sql = "INSERT INTO score(value,type,id) VALUES(?,?,?)";
		this.pstmt = this.conn.prepareStatement(sql);
		this.pstmt.setInt(1, score.getScore_value());
		this.pstmt.setString(2, score.getTarget_type());
		this.pstmt.setString(3, score.getTarget_id());
		
		if(pstmt.executeUpdate()!=0){
			flag = true;
		}
		this.pstmt.close();
		return flag;
	}
	public List<Score> findBuyerScoreSet(User buyer) throws Exception {
		List<Score> scores = new ArrayList<Score>();
		String sql = "SELECT * FROM score WHERE type=? AND id=?";
		this.pstmt = this.conn.prepareStatement(sql);
		this.pstmt.setString(1, "buyer");
		this.pstmt.setString(2, buyer.getUser_id());
		ResultSet rs = this.pstmt.executeQuery();
		while(rs.next()){
			Score i = getScoreFromRs(rs);
			scores.add(i);
		}
		this.pstmt.close();
		return scores;
	}
	public List<Score> findSellerScoreSet(User seller) throws Exception {
		List<Score> scores = new ArrayList<Score>();
		String sql = "SELECT * FROM score WHERE type=? AND id=?";
		this.pstmt = this.conn.prepareStatement(sql);
		this.pstmt.setString(1, "seller");
		this.pstmt.setString(2, seller.getUser_id());
		ResultSet rs = this.pstmt.executeQuery();
		while(rs.next()){
			Score i = getScoreFromRs(rs);
			scores.add(i);
		}
		this.pstmt.close();
		return scores;
	}
	public List<Score> findItemScoreSet(Item item) throws Exception {
		List<Score> scores = new ArrayList<Score>();
		String sql = "SELECT * FROM score WHERE type=? AND id=?";
		this.pstmt = this.conn.prepareStatement(sql);
		this.pstmt.setString(1, "item");
		this.pstmt.setString(2, Integer.toString(item.getItem_id()));
		ResultSet rs = this.pstmt.executeQuery();
		while(rs.next()){
			Score i = getScoreFromRs(rs);
			scores.add(i);
		}
		this.pstmt.close();
		return scores;
	}
	private Score getScoreFromRs(ResultSet rs){
		Score score = new Score();
		try {
			score.setScore_value(rs.getInt("value"));
			score.setTarget_type(rs.getString("type"));
			score.setTarget_id(rs.getString("id"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return score;
	}
	

}
